package com.itheima.mapper;

import com.itheima.bean.Student;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test01 {
    @Test
    public void selectAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("myBatisStudent.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        myBatisMapper mapper = sqlSession.getMapper(myBatisMapper.class);

        List<Student> students = mapper.selectAll();

        for (Student student : students) {
            System.out.println(student);
        }

        is.close();
        sqlSession.close();
    }
    @Test
    public void insert() throws Exception{
        InputStream resourceAsStream = Resources.getResourceAsStream("myBatisStudent.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        myBatisMapper mapper = sqlSession.getMapper(myBatisMapper.class);




        Student student=new Student(null,"王五",25);
        System.out.println("提交前"+student.getId());
        Student insert = mapper.insert(student);
        System.out.println("提交后"+student.getId());
        System.out.println(insert);


        resourceAsStream.close();
        sqlSession.close();

    }
    @Test
    public void update() throws Exception{
        InputStream resourceAsStream = Resources.getResourceAsStream("myBatisStudent.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        myBatisMapper mapper = sqlSession.getMapper(myBatisMapper.class);
        Student student =new Student(4,"王七",27);
        Integer update = mapper.update(student);
        System.out.println(update);
        resourceAsStream.close();
        sqlSession.close();


    }
    @Test
    public void delete() throws Exception{
        InputStream resourceAsStream = Resources.getResourceAsStream("myBatisStudent.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        myBatisMapper mapper = sqlSession.getMapper(myBatisMapper.class);
        Integer delete = mapper.delete(4);
        System.out.println(delete);
        resourceAsStream.close();
        sqlSession.close();

    }
}
